package cn.bookcycle.requestroom.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bookcycle.requestroom.ConstantData.BusinessConstant;
import cn.bookcycle.requestroom.ConstantData.DBConstant;
import cn.bookcycle.requestroom.pojo.DateRecord;
import cn.bookcycle.requestroom.pojo.RoomInfo;
import cn.bookcycle.requestroom.pojo.UserInfo;
import cn.bookcycle.requestroom.util.ApplyRoom;
import cn.bookcycle.requestroom.util.DaoUtil;
import cn.bookcycle.requestroom.util.DataFormatConvert;

/**
 * 接收看房请求
 *
 * @author liufenglin
 * @date 2018年3月4日
 */
@Controller
public class RequestRoomController {
	private static final Logger logger = LoggerFactory.getLogger(RequestRoomController.class);
	
	/**
	 * 解析看房请求
	 * 
	 * @return
	 */
	@RequestMapping(value = "checkroom", method = RequestMethod.POST)
	public String resolveRequestRoom(@RequestBody (required=false) String requestBody, Model model) {
		// 默认的返回结果
		String result = "";
		String userId = null;
		if (requestBody != null) {
			// 对接收到的数据进行URL解码
			try {
				requestBody = URLDecoder.decode(requestBody, BusinessConstant.UTF8);
			} catch (UnsupportedEncodingException e) {
				logger.warn("URL解码出现异常！！！！！");
			}
			logger.info("收到的看房请求参数：{}", requestBody);
			// 把key=value格式的requestBody转为Map
			Map map = DataFormatConvert.paraToMap(requestBody);
			logger.info("请求参数转化成的map：{}", map);
			// 根据map中的roomId参数获取一个房间的看房记录信息
			String checkRoomRecordJsonStr = null;
//			roomJsonStr = DaoUtil.getRoomById(map.get(DBConstant.ROOM_ID).toString());
			checkRoomRecordJsonStr = DaoUtil.getCheckRoomRecordById(map.get(DBConstant.ROOM_ID).toString());
			
			// 根据map中的userId参数获取用户信息
			userId = map.get(DBConstant.USER_ID).toString();
			String userJsonStr = DaoUtil.getUsedFreeChanceById(map.get(DBConstant.USER_ID).toString());
			// 把看房时间放入DataRecord
			DateRecord dateRecord = new DateRecord(map.get(BusinessConstant.DATE).toString(),
					Integer.valueOf(map.get(BusinessConstant.DURATION).toString()));
			logger.info("dateRecord的数据：date:{},duration:{}", dateRecord.getStartDate(), dateRecord.getDuration());
			// 把获取到的json格式信息转换为POJO类
			RoomInfo room = DataFormatConvert.jsonToRoom(map.get(DBConstant.ROOM_ID).toString(), checkRoomRecordJsonStr, dateRecord);
			logger.info("room的信息：{}, {}", room.getRoomId(), room.isEmpty());
 			UserInfo user = DataFormatConvert.jsonToUser(map.get(DBConstant.USER_ID).toString(), userJsonStr);
			// 房间为空，才进行后续申请操作
			if (room.isEmpty()) {
				// 看房类型（fee收费，free免费）
				String type = map.get(BusinessConstant.TYPE).toString();
				if (BusinessConstant.FEE.equals(type)) {
					// 为用户申请付费看房
					result = ApplyRoom.applyRoomFee(user, room, dateRecord);
				} else if (BusinessConstant.FREE.equals(type)) {
					// 为用户申请免费看房
					result = ApplyRoom.applyRoomFree(user, room, dateRecord);
				} else {
					// 其他类型，以后扩展
				}
			} else {
				// 房间不为空，就返回40006状态码
				result = BusinessConstant.ROOM_FILL;
				logger.info("房间不为空，不能看房！！");
			}
		} else { 
			// 如果请求体为空
		}
		// 把userId传到前台
		model.addAttribute(DBConstant.USER_ID, userId);
		String resultpage = null;
		if (BusinessConstant.SUCCESS_FEE.equals(result) || BusinessConstant.SUCCESS_FREE.equals(result)) {
			// 请求看房权限成功就返回陈成功页面
			resultpage = "success";
		} else {
			resultpage = "failure";
		}
		return resultpage;
	}
	
	/// FIXME 这部分逻辑不清楚，也不是核心业务，以后再补充
//	/**
//	 * 收到用户进入房间的消息，对房间进行监控
//	 * 
//	 * @return
//	 */
//	@ResponseBody
//	@RequestMapping(value = "/supervise", method = RequestMethod.POST)
//	public String monitorRoom(@RequestBody (required=false) String requestBody) {
//		return ""
//	}
}
